package com.example.NeteaseCloudMusicApi.ui.fragment;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.example.NeteaseCloudMusicApi.R;
import com.example.NeteaseCloudMusicApi.entity.LoginDTO;
import com.example.NeteaseCloudMusicApi.entity.Player;
import com.example.NeteaseCloudMusicApi.ui.APIService;
import com.example.NeteaseCloudMusicApi.ui.ConString;
import com.example.NeteaseCloudMusicApi.ui.adapter.PlayerAdapter;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PlayerFragment extends Fragment {
    RecyclerView recyclerView,playListRv,musicStoryRv,soundRv,recommendRv;
    LinearLayoutManager layoutManager,playListLm,musicStoryLm,soundLm,recommendLm;
    PlayerAdapter adapter;

    private List<Player> playerList = new ArrayList<>();

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public PlayerFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PlayerFragment newInstance(String param1, String param2) {
        PlayerFragment fragment = new PlayerFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //主线程中使用请求
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }


        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView =  inflater.inflate(R.layout.activity_player, container, false);

        initSong();
        initPlayer();
        //关注更新
        recyclerView = rootView.findViewById(R.id.follow_update);
        layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);

        //精选播单
        playListRv = rootView.findViewById(R.id.play_list);
        playListLm = new GridLayoutManager(getContext(),3);
        playListRv.setLayoutManager(playListLm);


        //音乐故事|安放你的每一种情绪
        musicStoryRv = rootView.findViewById(R.id.emotion);
        musicStoryLm = new LinearLayoutManager(getContext());
        musicStoryLm.setOrientation(LinearLayoutManager.HORIZONTAL);
        musicStoryRv.setLayoutManager(musicStoryLm);

        //声之剧场
        soundRv = rootView.findViewById(R.id.sound);
        soundLm = new LinearLayoutManager(getContext());
        soundLm.setOrientation(LinearLayoutManager.HORIZONTAL);
        soundRv.setLayoutManager(soundLm);

        //为你推荐
        recommendRv = rootView.findViewById(R.id.recommend);
        recommendLm = new LinearLayoutManager(getContext());
        recommendLm.setOrientation(LinearLayoutManager.HORIZONTAL);
        recommendRv.setLayoutManager(recommendLm);


        adapter = new PlayerAdapter(playerList);
        recyclerView.setAdapter(adapter);
        playListRv.setAdapter(adapter);
        musicStoryRv.setAdapter(adapter);
        soundRv.setAdapter(adapter);
        recommendRv.setAdapter(adapter);
        System.out.println("b");
        return rootView;

    }

        private void initSong() {
//        String path="http://music.163.com/api/playlist/detail?id=1";
//            System.out.println("c");
//        try {
//            //网络请求的方法
//            URL url = new URL(path);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            //请求方式
//            conn.setRequestMethod("GET");
//            //设置超时
//            conn.setConnectTimeout(5000);
//            //返回的状态码
//            int responseCode = conn.getResponseCode();
//            System.out.println("状态码："+responseCode);
//            if (responseCode == 200) {
//                System.out.println("d");
//                //将获取的数据转换为字符串
//                InputStream is = conn.getInputStream();
//                String response = getStringFromInputStream(is);
//                JSONObject jsonObject=new JSONObject(response);
//                JSONObject result = jsonObject.getJSONObject("result");
//                JSONArray tracks = result.getJSONArray("tracks");
//                System.out.println("数据个数"+tracks.length());
//
//                for (int i=0;i<tracks.length();i++){
//                    JSONObject jsonObject1=tracks.getJSONObject(i);
//                    JSONArray artists = jsonObject1.getJSONArray("artists");
//
//                    for (int j =0;j<1;j++){
//                        JSONObject jsonArray = artists.getJSONObject(j);
//                        String img1v1Url = jsonArray.getString("img1v1Url");
//                        String name = jsonArray.getString("name");
//                        System.out.println(img1v1Url);
//                        System.out.println(name);
//
//                        playerList.add(new Player(name,i ));
//                    }
////                    PlayerAdapter adapter=new  PlayerAdapter(playerList);
////                    recyclerView.setAdapter(adapter);
//
//                }
//
//
////                System.out.println(response);
//
////                //将信息存储  ，下次调用采用覆盖的方法
////                SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
////                editor.putString("allSongs",response);
////                editor.commit();
////                closeImm();
//            } else {
////                Result.failure(ResultCode.NET_REQUEST_FAILED);
//                System.out.println("请求状态非200——————————————————————————————————————————————");
//            }
//        } catch (Exception e) {
//            System.out.println("请求错误—————————————————————————————————————————————");
//
//        }

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ConString.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            APIService retrofitApi = retrofit.create(APIService.class);
            Call<Player> userCall = retrofitApi.getPlayer("1");
            userCall.enqueue(new Callback<Player>() {
                @Override
                public void onResponse(Call<Player> call, Response<Player> response) {
                    System.out.println(response);
                }
                @Override
                public void onFailure(Call<Player> call, Throwable t) {
                }
            });

//        for (int i = 0; i < 6; i++) {
//            Player player = new Player("龙哥合集", R.mipmap.playlist_1);
//            playerList.add(player);
//
//        }
    }

    //对请求得到数据的处理
    private String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 模板代码
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
        os.close();
        return state;
    }


   /* @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        initPlayer();
        //关注更新
        recyclerView = findViewById(R.id.follow_update);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);


        //精选播单
        playListRv = findViewById(R.id.play_list);
        playListLm = new GridLayoutManager(this,3);
        playListRv.setLayoutManager(playListLm);


        //音乐故事|安放你的每一种情绪
        musicStoryRv = findViewById(R.id.emotion);
        musicStoryLm = new LinearLayoutManager(this);
        musicStoryLm.setOrientation(LinearLayoutManager.HORIZONTAL);
        musicStoryRv.setLayoutManager(musicStoryLm);

        //声之剧场
        soundRv = findViewById(R.id.sound);
        soundLm = new LinearLayoutManager(this);
        soundLm.setOrientation(LinearLayoutManager.HORIZONTAL);
        soundRv.setLayoutManager(soundLm);

        //为你推荐
        recommendRv = findViewById(R.id.recommend);
        recommendLm = new LinearLayoutManager(this);
        recommendLm.setOrientation(LinearLayoutManager.HORIZONTAL);
        recommendRv.setLayoutManager(recommendLm);


        adapter = new PlayerAdapter(playerList);
        recyclerView.setAdapter(adapter);
        playListRv.setAdapter(adapter);
        musicStoryRv.setAdapter(adapter);
        soundRv.setAdapter(adapter);
        recommendRv.setAdapter(adapter);
    }
*/
    private void initPlayer() {

            Player app1 = new Player("龙哥合集", R.mipmap.playlist_1);
            playerList.add(app1);
            Player app2 = new Player("CMBYN合集", R.mipmap.playlist_2);
            playerList.add(app2);
            Player app3 = new Player("权游合集", R.mipmap.playlist_3);
            playerList.add(app3);
            Player app4 = new Player("土豆合集", R.mipmap.playlist_4);
            playerList.add(app4);
            Player app5 = new Player("ONE OK ROCK合集", R.mipmap.playlist_5);
            playerList.add(app5);
            Player app6 = new Player("杰尼斯west合集", R.mipmap.playlist_6);
            playerList.add(app6);
    }

}
